import {
  loginByUsername,
  logout,
  getUserInfo,
  getMenuList,
  scanLogin
} from '@/api/login'
// eslint-disable-next-line no-unused-vars
import { getToken, setToken, removeToken, setRole, getRole, setName, getName } from '@/utils/auth'

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    userType: '',
    introduction: '',
    roles: [],
    menus: [], // 菜单权限
    buttons: [], // 按钮权限
    buildings: [], // 楼栋权限
    setting: {
      articlePlatform: []
    },
    mdiUserId: '',
    singleProject: '',
    singleRole: '',
    currProjectId: '',
    currProjectName: '',
    currProjectRoleCode: '',
    currTenantId: '',
    currTenantName: '',
    empNo: '',
    brandCode: '',
    productPowerlist: [],
    productXzqhlist: [],
    materialTypelist: [],
    uploadPicUrl: '',
    merchantCode: ''
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_USERTYPE: (state, userType) => {
      state.userType = userType
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_BUTTONS: (state, buttons) => {
      state.buttons = buttons
    },
    SET_BUILDINGS: (state, buildings) => {
      state.buildings = buildings
    },
    SET_SINGLEPROJECT: (state, singleProject) => {
      state.singleProject = singleProject
    },
    SET_SINGLEROLE: (state, singleRole) => {
      state.singleRole = singleRole
    },
    SET_CURRPROJECTID: (state, currProjectId) => {
      state.currProjectId = currProjectId
    },
    SET_CURRPROJECTNAME: (state, currProjectName) => {
      state.currProjectName = currProjectName
    },

    SET_CURRPROJECTROLECODE: (state, currProjectRoleCode) => {
      state.currProjectRoleCode = currProjectRoleCode
    },

    SET_CURRTENANTID: (state, currTenantId) => {
      state.currTenantId = currTenantId
    },
    SET_CURRTENANTNAME: (state, currTenantName) => {
      state.currTenantName = currTenantName
    },
    SET_MDIUSERID: (state, mdiUserId) => {
      state.mdiUserId = mdiUserId
    },
    SET_EMPNO: (state, empNo) => {
      state.empNo = empNo
    },
    SET_BRANDCODE: (state, brandCode) => {
      state.brandCode = brandCode
    },
    SET_PRODUCTPOWERLIST: (state, productPowerlist) => {
      state.productPowerlist = productPowerlist
    },
    SET_PRODUCTXZQHLIST: (state, productXzqhlist) => {
      state.productXzqhlist = productXzqhlist
    },
    SET_MATERIALTYPELIST: (state, materialTypelist) => {
      state.materialTypelist = materialTypelist
    },
    SET_UPLOADPICURL: (state, uploadPicUrl) => {
      state.uploadPicUrl = uploadPicUrl
    },
    SET_MERCHANTCODE: (state, merchantCode) => {
      state.merchantCode = merchantCode
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password, userInfo.openid)
          .then(response => {
            const data = response.data
            commit('SET_TOKEN', data.token)
            setToken(response.data.token)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.token)
          .then(response => {
            // 由于mockjs 不支持自定义状态码只能这样hack
            if (!response.data) {
              reject('Verification failed, please login again.')
            }
            const data = response.data
            if (data.roles && data.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', data.roles)
            }
            // else {
            //   reject('getInfo: roles must be a non-null array!')
            // }

            if (data.menus && data.menus.length > 0) {
              // 验证返回的menus是否是一个非空数组
              commit('SET_MENUS', data.menus)
            }

            if (data.permissionList && data.permissionList.length > 0) {
              // 验证返回的buttons是否是一个非空数组
              commit('SET_BUTTONS', data.permissionList)
            }
            if (data.buildings && data.buildings.length > 0) {
              // 验证返回的buildings是否是一个非空数组
              commit('SET_BUILDINGS', data.buildings)
            }

            commit('SET_MERCHANTCODE', data.merchantCode)
            commit('SET_NAME', data.username)
            commit('SET_AVATAR', data.avatar)
            commit('SET_USERTYPE', data.userType)
            commit('SET_INTRODUCTION', data.username)
            // commit("SET_INTRODUCTION", data.introduction);
            // commit("SET_SINGLEPROJECT", data.singleProject);
            // commit("SET_SINGLEROLE", data.singleRole);
            // commit("SET_CURRPROJECTID", data.currProjectId);
            // commit("SET_CURRPROJECTNAME", data.currProjectName);
            // commit("SET_CURRPROJECTROLECODE", data.currProjectRoleCode);
            // commit("SET_CURRTENANTID", data.currTenantId);
            // commit("SET_CURRTENANTNAME", data.currTenantName);
            commit('SET_MDIUSERID', data.userId)
            // commit("SET_EMPNO", data.empNo);
            commit('SET_BRANDCODE', '001')

            // commit("SET_UPLOADPICURL", data.uploadPicUrl);

            if (data.productPowerlist && data.productPowerlist.length > 0) {
              // 验证返回的productPowerlist是否是一个非空数组
              commit('SET_PRODUCTPOWERLIST', data.productPowerlist)
            }
            if (data.productXzqhlist && data.productXzqhlist.length > 0) {
              // 验证返回的productXzqhlist是否是一个非空数组
              commit('SET_PRODUCTXZQHLIST', data.productXzqhlist)
            }
            if (data.materialTypelist && data.materialTypelist.length > 0) {
              // 验证返回的productXzqhlist是否是一个非空数组
              commit('SET_MATERIALTYPELIST', data.materialTypelist)
            }

            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取menu信息
    GetMenuList({ commit }) {
      return new Promise((resolve, reject) => {
        getMenuList()
          .then(response => {
            // 由于mockjs 不支持自定义状态码只能这样hack
            if (!response.data) {
              reject('Verification failed, please login again.')
            }
            const data = response.data
            if (data && data.length > 0) {
              // 验证返回的menus是否是一个非空数组
              commit('SET_MENUS', data)
            }
            // TODO huwg，替换为服务端返回
            commit('SET_ROLES', ['ADMIN', 'ROLE_ADMIN'])
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 第三方验证登录
    LoginByThirdparty({ commit, state }, code) {
      return new Promise((resolve, reject) => {
        // commit('SET_CODE', code)
        scanLogin(code)
          .then(response => {
            if (response.data.token) {
              commit('SET_TOKEN', response.data.token)
              setToken(response.data.token)
            }
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({ commit, dispatch }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_MENUS', data.menus)
          commit('SET_BUTTONS', data.buttons)

          commit('SET_NAME', data.userName)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          commit('SET_SINGLEPROJECT', data.singleProject)
          commit('SET_SINGLETENANT', data.singleTenant)
          commit('SET_CURRPROJECTID', data.currProjectId)
          commit('SET_CURRPROJECTNAME', data.currProjectName)
          commit('SET_CURRTENANTID', data.currTenantId)
          commit('SET_CURRTENANTNAME', data.currTenantName)

          dispatch('GenerateRoutes', data.menus) // 动态修改权限后 重绘侧边菜单
          resolve()
        })
      })
    }
  }
}

export default user

